package com.example.boot.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.LogAnno;
import com.example.common.Result;
import com.example.common.enums.KeyEnum;
import com.example.common.enums.LogType;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.exception.CustomException;
import com.example.pojo.dto.ValidDTO;
import com.example.pojo.entity.Admin;
import com.example.pojo.entity.Contract;
import com.example.service.ContractService;
import com.example.service.ProjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * TODO
 *
 * @author ding
 * @since 2024/6/2
 */
@RestController
@RequestMapping("/contract")
@Slf4j
@Api(tags = "合同管理相关接口")
public class ContractController {
    @Autowired
    private ContractService contractService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 获取全部合同信息
     */
    @GetMapping("/selectAll")
    public Result selectAll(){
        List<Contract> contractList = contractService.selectAll();
        return Result.success(contractList);
    }

    /**
     * 根据id获取合同文件信息
     */
//    @PreAuthorize("hasAuthority('CONTRACT_QUERY')")
    @GetMapping("/getById/{id}")
    public Result selectById(@PathVariable Integer id){
        contractService.getById(id);
        return Result.success();
    }

    /**
     * 分页获取项目合同信息
     * @param pageSize      每页页数
     * @param pageNum       当前页数
     * @param teamName      施工队名称
     * @param projectName   项目名称
     * @param order         排序规则
     * @return              返回合同信息列表
     */
//    @PreAuthorize("hasAuthority('CONTRACT_QUERY')")
    @GetMapping("/page")
    public Result selectPage(@RequestParam(defaultValue = "10") Integer pageSize,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             String teamName,String projectName, String order){
        Page<Contract> page = contractService.selectByPage(pageNum, pageSize, teamName, projectName, order);
        return Result.success(page);
    }

    /**
     * 根据id删除合同信息
     * @param id    合同id信息
     */
    @LogAnno(title = "合同管理", type = LogType.DELETE)
//    @PreAuthorize("hasAuthority('CONTRACT_DELETE')")
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Integer id){
        contractService.deleteById(id);
        return Result.success();
    }

    /**
     * 根据id集合批量删除合同信息
     * @param ids   id集合信息
     */
    @LogAnno(title = "合同管理", type = LogType.DELBATCH)
//    @PreAuthorize("hasAuthority('CONTRACT_DELETE')")
    @DeleteMapping("/delBatch")
    public Result delBatch(@RequestBody List<Integer> ids){
        contractService.delBatch(ids);
        return Result.success();
    }

//    @PreAuthorize("hasAuthority('CONTRACT_DELETE')")
    @PostMapping("/validSms")
    public Result validSms(@RequestBody ValidDTO validDTO){
        if (ObjectUtil.isEmpty(validDTO)) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        String mobile = validDTO.getMobile();
        String valid = validDTO.getSms();
        String code = redisTemplate.opsForValue().get(KeyEnum.VALID_KEY + "_" + mobile + "_" + valid);
        if (!StringUtils.hasLength(code)) {
            throw new CustomException(ResultCodeEnum.SMS_EXPIRE_ERROR);
        }
        if (valid.equals(code)){
            return Result.success("校验成功");
        }
        else return Result.error(ResultCodeEnum.SMS_VALID_ERROR);
    }

    @ApiOperation("下载项目合同模版")
//    @PreAuthorize("hasAuthority('CONTRACT_LOAD')")
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws UnsupportedEncodingException {
        File file = null;
        try {
             file = ResourceUtils.getFile("classpath:doc/项目合作协议书模版.docx");
        }catch(Exception e){
            log.warn("模版文件未找到");
            return;
        }

        if (file != null && file.isFile()) {
            String fileName = file.getName();

            response.reset();
            response.setContentType("application/force-download");
            response.setCharacterEncoding("utf-8");
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            try(
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                    BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            ){
                byte[] bytes = new byte[1024];
                int len = -1;
                while ((len=bis.read(bytes))!= -1) {
                    bos.write(bytes, 0, len);
                    bos.flush();
                }
                log.info("文件下载完成！！");
            }catch(Exception e){
                log.error("模版文件下载失败，理由是：{}", e.getMessage());

            }
        }
    }
}
